package com.ubiquando.api.server;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.KeyFactory;
import com.ubiquando.api.server.db.Client;
import com.ubiquando.api.server.db.Dao;

public class Register extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1665715219044644231L;

	private static final Logger log = Logger.getLogger(Register.class.getName());
	
//	@Override
//	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
//			throws ServletException, IOException {
//		resp.setContentType("application/json");
//		String name = req.getParameter("name");
//		String location = req.getParameter("location");
//		String regId = req.getParameter("registrationId");
//		String email = req.getParameter("email");
//		String pwd = req.getParameter("pwd");
//		String clientLogin = req.getParameter("clientLogin");
//		
//		log.info("In register servlet received: name="+name+" location="+location+
//				" registration_id=******* clientLogin=*******");
//		
//		Client newClient = Dao.INSTANCE.addClient(name, email, pwd, location, regId, clientLogin);
//		
//		System.out.println("name: "+newClient.getName());
//		System.out.println("location: "+newClient.getLocation());
//		System.out.println("email: "+newClient.getEmail());
//		System.out.println("pwd: "+newClient.getPwd());
//		System.out.println("clientLogin: "+newClient.getClientLoginToken());
//		
//		
//		log.info("Added client "+KeyFactory.keyToString(newClient.getId()));
//		
//		MyJsonWriter.returnClientID(resp.getWriter(), KeyFactory.keyToString(newClient.getId()));
//	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/json");
		String name = req.getParameter("name");
		String email = req.getParameter("email");
		String pwd = req.getParameter("pwd");
		String location = req.getParameter("location");
		String regId = req.getParameter("registrationId");
//		String clientLogin = req.getParameter("clientLogin");
		
		log.info("In register servlet received: name="+name+" location="+location+
				" registration_id=******* clientLogin=*******");
		
		Client newClient = Dao.INSTANCE.addClient(name, email, pwd, location, regId/*, clientLogin*/);
		
		if(newClient == null){
			MyJsonWriter.returnError(resp.getWriter(), "client exists");
			log.info("returned error");
		}
		log.info("Added client "+KeyFactory.keyToString(newClient.getId()));
		
		MyJsonWriter.returnClientID(resp.getWriter(),KeyFactory.keyToString(newClient.getId()));
	}
}
